<template>
  <div class="h-full app-container relative text-sm">
    <div class="bg-white h-full relative">
      <div class="form-container">
        <div class="p-[10px]">
          <span>充值</span>
        </div>
        <div class="mb-[20px] h-[1px] w-full bg-[#f6f6f6]"></div>
        <div class="bg-[#f7f7f7] h-[40px] leading-[40px] m-[10px] p-[10px] py-0">
          <span class="color-[#6b6b6b]">充值给</span>
          <span class="font-bold">南昌云筑树栖数据服务有限公司</span>
        </div>
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="300px"
          class="form mb-0"
        >
          <el-form-item label="可用积分">
            <span v-loading="balanceLoading" class="color-[#a43e42]">{{ balanceTotal || 0 }}</span>
            <el-icon style="margin-left: 20px" @click="onClickOutside">
              <InfoFilled />
            </el-icon>
          </el-form-item>
          <el-form-item label="充值方式" prop="type">
            <el-radio-group
              v-model="formData.type"
              class="!w-[220px]"
              :disabled="loading"
              @change="handleChangeType"
            >
              <div class="flex items-center">
                <div
                  v-for="item in options"
                  :key="item.value"
                  :class="{ 'border-[#79a6ff] border': item.value === formData.type }"
                  class="w-[240px] h-[50px] flex justify-between items-center bg-[#f7f8fa] p-[20px] mr-2"
                >
                  <el-radio :label="item.value">
                    {{ item.label }}
                  </el-radio>
                  <div class="w-[40px] h-[40px]">
                    <img :src="item.icon" class="h-full w-full" />
                  </div>
                </div>
              </div>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="充值金额（1元等于10积分）" prop="amount">
            <el-input-number
              v-model="formData.amount"
              :disabled="loading"
              :min="0.1"
              :step="1"
              :max="50000"
              class="!w-[220px]"
              placeholder="请输入金额"
            />
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" :loading="loading" @click="handleSubmit">去支付</el-button>
          </el-form-item>
          <el-form-item v-if="isShowQrcode" label="">
            <qrcode-vue
              :value="qrcode"
              :size="300"
              level="H"
              render-as="svg"
              :image-settings="imageSettings"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="mb-[30px] h-[1px] w-full bg-[#f6f6f6] absolute bottom-[20px]"></div>
      <!--      <div class="absolute bottom-[10px] left-[10px]">
        <el-checkbox v-model="certificate" :true-value="1" :false-value="0"></el-checkbox>
        <span>
          我已知晓：
          <span class="color-[#a43e42]">费用将由南昌云筑数据服务有限公司统一收取</span>
          ，并已阅读
          <span class="color-[#79a6ff] cursor-pointer">《在线支付须知》</span>
          <span class="color-[#79a6ff] cursor-pointer">《服务协议》</span>
        </span>
      </div> -->
    </div>
    <recharge-form ref="rechargeFormRef"></recharge-form>
    <Agreement ref="communityGuideLinesRef" keys="merchantCoinsRule"></Agreement>
  </div>
</template>
<script setup lang="ts">
import coinsAPI, { PaymentOrderQuery, PaymentQueryForm } from "@/api/coins/coins-api";
import { PAY_METHOD_ENUM, RECHARGE_STATUS_ENUM } from "@/enums/conins/ConinsEnum";
import { ElMessage } from "element-plus";
import { getLabelValueList } from "@/utils/enums";
import { useBalance } from "@/hooks/useBalance";
import RechargeForm from "@/views/coins/recharge/components/recharge-form.vue";
const { balanceTotal, loading: balanceLoading, getBalanceTotal } = useBalance();
import QrcodeVue, { ImageSettings } from "qrcode.vue";
import wx from "@/assets/images/pay/wx.png";
import { ref, unref } from "vue";
import { ClickOutside as vClickOutside } from "element-plus";
import Agreement from "@/components/Agreement/index.vue";

const loading = ref(false);
const formRef = ref();
const rechargeFormRef = ref();
const qrcode = ref("");
const imageSettings: ImageSettings = {
  src: wx,
  height: 64, // The height of image
  width: 64, // The height of image
  excavate: true, // Whether to excavate the image
};
const options = getLabelValueList(PAY_METHOD_ENUM);
const certificate = ref(1);
const defaultFormData: PaymentOrderQuery = {
  amount: null,
  subject: "积分充值",
  type: PAY_METHOD_ENUM.WECHAT.value,
};
const id = ref();
const timeOutId = ref();
const intervalTime = 5 * 1000;
const timeOut = 60 * 1000;
const formData = ref({
  ...defaultFormData,
});
const popoverRef = ref();

const validateAmount = (rule: any, value: any, callback: any) => {
  if (!value && value !== 0) {
    callback(new Error("请输入金额"));
  } else if (value === 0.1) {
    callback();
  } else if (value >= 1 && Number.isInteger(value)) {
    callback();
  } else {
    callback(new Error("金额格式不正确"));
  }
};

const formRules = reactive({
  amount: [
    { required: true, message: "请输入金额", trigger: "blur" },
    { type: "number", message: "金额必须为数字" },
    { type: "number", max: 50000, message: "金额超出最大值，最多可充值5万元" },
    { validator: validateAmount, trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择支付方式", trigger: "change" }],
  certificate: [{ required: true, message: "请上传付款凭证", trigger: "change" }],
  rechargeTime: [{ required: true, message: "请选择充值时间", trigger: "change" }],
});

const isShowQrcode = computed(() => {
  return formData.value.type === PAY_METHOD_ENUM.WECHAT.value && qrcode.value;
});

async function handleSubmit() {
  // if (certificate.value === 0) return ElMessage.error("请阅读并同意服务协议");
  const validate = await formRef.value.validate();
  if (!validate) return;
  handleWechatPay();
}

async function handleWechatPay() {
  try {
    loading.value = true;
    const {
      data: { content, outTradeNo },
    } = await coinsAPI.getWebQrcode(formData.value);
    qrcode.value = content;
    id.value = setInterval(() => {
      getPayStatus(outTradeNo);
    }, intervalTime);
    timeOutId.value = setTimeout(() => {
      cancel();
      ElMessage.error("支付超时!请重新发起支付!");
    }, timeOut);
    ElMessage.success("请扫码支付");
  } catch (error) {
    console.log("error", error);
    ElMessage.error("支付失败");
    loading.value = false;
  }
}

async function handleAliPay() {
  try {
    loading.value = true;
    const res = await coinsAPI.getWebQrcode(formData.value);
    const { content, outTradeNo } = res.data;
    gotoPay(content);
  } catch (error) {
    console.log("error", error);
    ElMessage.error("支付失败");
  } finally {
    loading.value = false;
  }
}

function gotoPay(content) {
  const dom = document.createElement("div");
  dom.innerHTML = content;
  document.body.appendChild(dom);
  const form = document.getElementsByName("punchout_form");
  form[0].setAttribute("target", "_blank");
  form[0].submit();
  document.body.removeChild(dom);
}

const communityGuideLinesRef = ref();

function onClickOutside() {
  communityGuideLinesRef.value.showModal();
}

async function getPayStatus(outTradeNo) {
  try {
    const params: PaymentQueryForm = {
      outTradeNo,
      type: formData.value.type,
    };
    const { data } = await coinsAPI.getByOutTradeNoApi(params);
    if (data === RECHARGE_STATUS_ENUM.SUCCESS.value) {
      cancel();
      ElMessage.success("支付成功，请到积分账单中查看。");
      getBalanceTotal();
    }
  } catch (e) {
    console.log(e);
    cancel();
  }
}

function cancel() {
  clearInterval(id.value);
  clearTimeout(timeOutId.value);
  qrcode.value = "";
  formData.value.amount = null;
  loading.value = false;
}

function handleChangeType() {
  cancel();
}

onBeforeUnmount(() => {
  clearInterval(id.value);
  loading.value = false;
});
</script>

<style scoped lang="scss">
.a {
  font-weight: bold;
  cursor: pointer;
}
.form-div-text {
  height: 500px;
  overflow: scroll;
}
</style>
